#pragma once
#include <iostream>
#include <pthread.h>
#include <vector>
#include "Task.hpp"
#include <unistd.h>
// #include "./thread/thread.hpp"

// 单例模式的使用
using namespace std;
struct threadInfo
{
    string threadname;
    pthread_t tid;
};

static const int DefaultNUM = 5;

template <class T>
class ThreadPool
{
private:
    pthread_t tid;
    pthread_mutex_t mutex_;
    pthread_cond_t cond_;

    vector<threadInfo> threads_;

    vector<Task> tasks_;

public:
    void
    Lock()
    {
        pthread_mutex_lock(&mutex_);
    }
    void Unlock()
    {
        pthread_mutex_unlock(&mutex_);
    }
    void WakeUp()
    {
        pthread_cond_signal(&cond_);
    }
    void threadsleep()
    {
        pthread_cond_wait(&cond_, &mutex_);
    }

public:
    void push(const T &t)
    {
        Lock();
        tasks_.push_back(t);
        WakeUp();
        Unlock();
    }
    T Pop()
    {
        T t = tasks_.front();
        tasks_.pop_back();
        return t;
    }
    string getname(pthread_t tid)
    {
        for (auto &i : threads_)
        {
            if (i.tid = tid)
                return i.threadname;
        }
        return "None";
    }

    static void *HandlerTask(void *args)
    {
        ThreadPool<T> *tp = static_cast<ThreadPool<T> *>(args);
        while (true)
        {
            tp->Lock();
            while (tp->tasks_.empty())
            {
                tp->threadsleep();
            }
            Task t;
            t = tp->Pop();
            tp->Unlock();
            t.run();
            cout << tp->getname(pthread_self()) << " run," << t.GetResult() << endl;
            // sleep(1);
        }
    }

    void Start()
    {

        for (int i = 0; i < threads_.size(); i++)
        {
            threads_[i].threadname = "thread-" + to_string(i + 1);
            pthread_create(&(threads_[i].tid), NULL, HandlerTask, this);
        }
    }

private:
    static ThreadPool<T> *td_;
    static pthread_mutex_t lock_;
    ThreadPool(int num = DefaultNUM) : threads_(num)
    {
        pthread_mutex_init(&mutex_, NULL);
        pthread_cond_init(&cond_, NULL);
    }
    ~ThreadPool()
    {
        pthread_mutex_destroy(&mutex_);
        pthread_cond_destroy(&cond_);
    }

public:
    static ThreadPool<T> *GetInterface()
    {
        if (NULL == td_)
        {
            pthread_mutex_lock(&lock_);
            if (NULL == td_)
            {
                std::cout << "log: singleton create done first!" << std::endl;
                td_ = new ThreadPool<T>();
            }
            pthread_mutex_unlock(&lock_);
        }
        return td_;
    }
};
template <class T>
ThreadPool<T> *ThreadPool<T>::td_ = NULL;

template <class T>
pthread_mutex_t ThreadPool<T>::lock_ = PTHREAD_MUTEX_INITIALIZER;
